// Call it like this:
// $(’ul.column’).smartColumns();
// 
// Or hand in the custom options:
// $(’ul.column’).smartColumns({ minWidth : 300, autoResize : false });

(function($) {

	var $that,plugin,opts,$c;

	$.fn.smartColumns = (function() {
		
		
		plugin = arguments.callee;
		//console.log(plugin);
		return function(options) {
			
			opts = $.extend({}, plugin.defaults, options);
			// Create a static property on smartColumns object to hold an array
			// of the jQuery collections used each time the plugin is invoked
			plugin.$collections = plugin.$collections || [];
			$c = $c || plugin.$collections;
			
			return $(this).each(function(){
				
				var columnW;

				// Each time the viewport is adjusted/resized, resize the columns
				//if(opts.autoResize) $(window).resize(function () { plugin.renderColumns(); });

				

				// Add this jQuery object
				$c[$c.length] = $(this);
				columnW = $c[$c.length-1].columnW = $(this).children().width();

				plugin.renderColumns($(this),columnW);				
			});

		}
		
	})();

	// make public so method can be called like $.fn.smartColumns.renderColumns()
	plugin.renderColumns = function($colContainers, columnW) { 
		
		var $colContainers = $colContainers;
		var columnW = columnW;
		
		var renderColumns = function($colContainers, columnW) {
			
			$colContainers.css({ 'width' : "100%"});

			var colWrap = $colContainers.width();
			var colNum = Math.floor(colWrap / opts.minWidth);
			var colFixed = Math.floor(colWrap / colNum);

			$colContainers.css({ 'width' : colWrap})
			$colContainers.children().css({ 'width' : colFixed});
		}

		if(typeof $colContainers != 'array' && $c.length > 0) { // if being invoked by resize
			var i = $c.length;
			while (i--) renderColumns($c[i]);
			console.log('what!');
		} else {
			console.log('blah blah');
			renderColumns($colContainers, columnW);
		}
	}

	// make public so users can change defaults
	plugin.defaults = { 
		minWidth : 200,
		autoResize : true
	};

})(jQuery);
